import { Injectable } from '@angular/core';

import { HttpClient } from "@angular/common/http";
import * as wellknown from 'wellknown';
import * as  turf from '@turf/turf';
import { MapService } from './map.service';

@Injectable({
  providedIn: 'root'
})
export class StyleService {
  layerIDs = ['defaultPolygonID', 'highlightPolygonID', 'lightLinetyleID', 'defaultPointID', 'highlightPointID', 'cctvStyleID', 'cctv-icon',
    'defaultLineID', 'highlightLineID', 'geo.ami.diffus', 'highlightRainLineID', 'highlightRainPointID',
    'highlightSewageLineID', 'highlightSewagePointID'];
  questionIDs = ['questionPointID', 'questionLineID', 'questionPloyID', 'highLightQuestionPointID'];
  iQueryIDs = ['queryPointID', 'queryLineID'];
  animationPoint = ['geo.ami.diffus'];
  private styleConfig = null;
  //  all - 点图层默认样式
  defaultPointStyle = {
    type: 'circle',
    id: 'defaultPointID',
    source: {
      type: 'geojson',
      data: null
    },
    paint: {
      'circle-radius': {
        "stops": [
          [5, 1],
          [10, 2],
          // zoom is 5 -> circle radius will be 1px
          [15, 3],
          // zoom is 10 -> circle radius will be 2px
          [20, 6]
        ]
      },
      'circle-stroke-color': 'rgba(255, 255, 255, 1)',
      'circle-stroke-width': 2,
      'circle-color': 'rgba(12, 239, 216, 0.8)'
    }
  };
  //  page - 点图层默认样式
  highlightPointStyle = {
    type: 'circle',
    id: 'highlightPointID',
    source: {
      type: 'geojson',
      data: null
    },
    paint: {
      'circle-radius': 8,
      'circle-color': 'rgba(12, 239, 216, 0.5)',
      'circle-stroke-color': 'rgba(255, 255, 255, 1)',
      'circle-stroke-width': 2,
    }
  };
  // all - 线图层默认样式
  defaultLinetyle = {
    type: 'line',
    id: 'defaultLineID',
    source: {
      type: 'geojson',
      data: null
    },
    layout: {
      'line-cap': 'round',
      'line-join': 'round'
    },
    paint: {
      'line-color': 'rgba(12, 239, 216, 1)',
      'line-width': 4
    }
  };
  // all - 线图层gaoliang样式
  highlightLinetyle = {
    type: 'line',
    id: 'highlightLineID',
    source: {
      type: 'geojson',
      data: null
    },
    layout: {
      'line-cap': 'round',
      'line-join': 'round'
    },
    paint: {
      'line-color': 'rgba(12, 239, 216, 0.8)',
      'line-width': 4
    }
  };

  lightLinetyle = {
    type: 'line',
    id: 'lightLinetyleID',
    source: {
      type: 'geojson',
      data: null
    },
    layout: {
      'line-cap': 'round',
      'line-join': 'round'
    },
    paint: {
      'line-color': 'rgba(12, 239, 216, 0.8)',
      'line-width': 4
    }
  };
  // all - 面图层默认样式
  defaultPolygontyle = {
    type: 'fill',
    id: 'defaultPolygonID',
    source: {
      type: 'geojson',
      data: null
    },
    layout: {},
    paint: {
      'fill-color': 'rgba(12, 239, 216, 0.5)',
      'fill-outline-color': 'rgba(0, 152, 196, 1)'

    }
  };
  // page - 面图层默认样式
  highlightPolygontyle = {
    type: 'fill',
    id: 'highlightPolygonID',
    source: {
      type: 'geojson',
      data: null
    },
    layout: {},
    paint: {
      'fill-color': 'rgba(12, 239, 216, 0.8)',
      'fill-outline-color': 'rgba(0, 152, 196, 1)'
    }
  };
  // --------------------------新增，---------------------------------------
  // 高亮雨水管线样式
  highlightRainLineStyle = {
    type: 'line',
    id: 'highlightRainLineID',
    source: {
      type: 'geojson',
      data: null
    },
    layout: {
      'line-cap': 'round',
      'line-join': 'round'
    },
    paint: {
      'line-color': 'rgba(26, 220, 132, 0.5)',
      'line-width': 4
    }
  };

  // 高亮雨水管点样式
  highlightRainPointStyle = {
    type: 'circle',
    id: 'highlightRainPointID',
    source: {
      type: 'geojson',
      data: null
    },
    paint: {
      'circle-radius': 6,
      'circle-color': 'rgba(31, 188, 255, 0.5)',
      'circle-stroke-color': 'rgba(255, 255, 255, 1)',
      'circle-stroke-width': 2,
    }
  };
  // 高亮污水管线样式
  highlightSewageLineStyle = {
    type: 'line',
    id: 'highlightSewageLineID',
    source: {
      type: 'geojson',
      data: null
    },
    layout: {
      'line-cap': 'round',
      'line-join': 'round'
    },
    paint: {
      'line-color': 'rgba(255, 8, 27, 0.5)',
      'line-width': 4
    }
  };

  // 高亮污水管点样式
  highlightSewagePointStyle = {
    type: 'circle',
    id: 'highlightSewagePointID',
    source: {
      type: 'geojson',
      data: null
    },
    paint: {
      'circle-radius': 6,
      'circle-color': 'rgba(230, 104, 0, 0.5)',
      'circle-stroke-color': 'rgba(255, 255, 255, 1)',
      'circle-stroke-width': 2,
    }
  };

  // ----------------------------问题标注信息样式-------------------------------------
  questionPointStyle = {
    id: 'questionPointID',
    type: 'symbol',
    source: {
      type: 'geojson',
      data: null
    },
    paint: {
      'text-color': '#fff',
      'text-halo-color': '#FFFFFF'
    },
    layout: {
      'icon-image': [
        'match',
        ['get', 'resolvestate'],
        1,
        'solve-point',
        0,
        'unsolve-point',
        'unsolve-point' // 说明：除了上诉两种不同的匹配规则外，还需要增加一个默认的样式！所以最后又写了一个！
      ],
      'icon-offset': [0, 0],
      'icon-allow-overlap': true,
      'icon-size': 1,
      'icon-anchor': 'bottom',
      'text-size': 12,
      'text-font': ['MicrosoftYaHeiBold'],
      'text-offset': [0.2, -1.5],
      'text-anchor': 'center',
      'text-field': ['to-string', ['get', 'id']], // 更换匹配属性！
      'text-justify': 'center',
    }
  };
  highLightQuestionPointstyle = {
    id: 'highLightQuestionPointID',
    type: 'symbol',
    source: {
      type: 'geojson',
      data: null
    },
    paint: {
      'text-color': '#fff',
      'text-halo-color': '#FFFFFF'
    },
    layout: {
      'icon-image': [
        'match',
        ['get', 'resolvestate'],
        1,
        'hl-solve-point',
        0,
        'hl-unsolve-point',
        'hl-unsolve-point' // 说明：除了上诉两种不同的匹配规则外，还需要增加一个默认的样式！所以最后又写了一个！
      ],
      'icon-offset': [0, 0],
      'icon-allow-overlap': true,
      'icon-size': 1,
      'icon-anchor': 'bottom',
      'text-size': 12,
      'text-font': ['MicrosoftYaHeiBold'],
      'text-offset': [0.2, -1.5],
      'text-anchor': 'center',
      'text-field': ['to-string', ['get', 'id']], // 更换匹配属性！
      'text-justify': 'center',
    }
  };
  // 原来点的样式unsolve-point
  // questionPointStyle = {
  //   type: 'circle',
  //   id: 'questionPointID',
  //   source: {
  //     type: 'geojson',
  //     data: null
  //   },
  //   paint: {
  //     'circle-radius': 6,
  //     'circle-stroke-color': 'rgba(255, 255, 255, 1)',
  //     'circle-stroke-width': 2,
  //     'circle-color': [
  //       'match',
  //       ['get', 'resolvestate'],
  //       1,
  //       'rgba(0, 128, 0, 0.5)',
  //       0,
  //       'rgba(255, 0, 0, 0.5)',
  //       /* other */ 'rgba(12, 239, 216, 0.5)'
  //       ]
  //   }
  // };
  questionLineStyle = {
    type: 'line',
    id: 'questionLineID',
    source: {
      type: 'geojson',
      data: null
    },
    layout: {
      'line-cap': 'round',
      'line-join': 'round'
    },
    paint: {
      'line-color': [
        'match',
        ['get', 'resolvestate'],
        1,
        'rgba(0, 128, 0, 0.5)',
        0,
        'rgba(255, 0, 0, 0.5)',
      /* other */ 'rgba(12, 239, 216, 0.5)'
      ],
      'line-width': 4
    }
  };
  questionPolyStyle = {
    type: 'fill',
    id: 'questionPloyID',
    source: {
      type: 'geojson',
      data: null
    },
    layout: {},
    paint: {
      'fill-color': [
        'match',
        ['get', 'resolvestate'],
        1,
        'rgba(0, 128, 0, 0.5)',
        0,
        'rgba(255, 0, 0, 0.5)',
      /* other */ 'rgba(12, 239, 216, 0.5)'
      ],
      'fill-outline-color': 'rgba(0, 152, 196, 1)'
    }
  };
  // -----------------------问题标注信息样式-------------------------



  // -----------------------------------------------------

  // 图片样式
  iconStyle = {
    id: 'e-point',
    type: 'symbol',
    source: {
      type: 'geojson',
      data: null
    },
    paint: {
      'text-color': '#fff',
      'text-halo-color': '#FFFFFF'
    },
    layout: {
      'icon-image': 'e-point',
      'icon-offset': [0, 0],
      'icon-allow-overlap': false,
      'icon-size': 1,
      'icon-anchor': 'bottom',
      'text-size': 12,
      'text-font': ['MicrosoftYaHeiBold'],
      'text-offset': [0, -1.5],
      'text-anchor': 'center',
      'text-field': ['to-string', ['get', 'title']],
      'text-justify': 'center'
    }
  };
  editIcon = {
    id: 'editIconID',
    type: 'symbol',
    source: {
      type: 'geojson',
      data: null
    },
    paint: {
      'text-color': '#fff',
      'text-halo-color': '#FFFFFF'
    },
    layout: {
      'icon-image': 'editIconID',
      'icon-offset': [0, 0],
      'icon-allow-overlap': false,
      'icon-size': 1,
      'icon-anchor': 'bottom',
      'text-size': 12,
      'text-font': ['MicrosoftYaHeiBold'],
      'text-offset': [0, -1.5],
      'text-anchor': 'center',
      'text-field': ['to-string', ['get', 'title']],
      'text-justify': 'center'
    }
  };
  // 图片样式
  cctvStyle = {
    id: 'cctvStyleID',
    type: 'circle',
    source: {
      type: 'geojson',
      data: null
    },
    paint: {
      'circle-radius': 18,
      'circle-color': 'rgba(12, 239, 216, 0.8)',
      'text-color': '#fff',
      'text-halo-color': '#FFFFFF'
    },
    layout: {
      'text-size': 12,
      'text-font': ['MicrosoftYaHeiBold'],
      'text-offset': [0, -1.5],
      'text-anchor': 'center',
      'text-field': ['to-string', ['get', 'title']],
      'text-justify': 'center'
    }
  };
  // 动画图片样式
  animatedDiffusionStyle = {
    id: 'geo.ami.diffus',
    type: 'symbol',
    source: {
      type: 'geojson',
      data: null
    },
    paint: {
      // "text-color": 'red',
      // "text-halo-color": "#FFFFFF"
    },
    layout: {
      'icon-image': 'geo.ami.diffus',
      'icon-offset': [0, 0],
      'icon-allow-overlap': false,
      'icon-rotation-alignment': 'map',
      'icon-size': 1,
    }
  };

  // i查询红色标识点
  iQueryPointStyle = {
    type: 'circle',
    id: 'queryPointID',
    source: {
      type: 'geojson',
      data: null
    },
    paint: {
      'circle-radius': 6,
      'circle-stroke-color': 'rgba(255, 255, 255, 1)',
      'circle-stroke-width': 2,
      'circle-color': 'rgba(255, 0, 0, 0.5)'
    }
  };
  iQueryLineStyle = {
    type: 'line',
    id: 'queryLineID',
    source: {
      type: 'geojson',
      data: null
    },
    layout: {
      'line-cap': 'round',
      'line-join': 'round'
    },
    paint: {
      'line-color': 'rgba(255, 0, 0, 0.5)',
      'line-width': 4
    }
  };


  constructor(
    private http: HttpClient,
    private mapService: MapService
  ) {
    this.getConfig().then((results: any) => {
      this.styleConfig = results[0];
      // this.symbolLayerIcons = results[2];
    });
  }
  // default_point 默认点样式； hightlight_point 选中点样式
  // default_line 默认点样式； hightlight_line 选中点样式
  //  default_polygon 默认点样式； hightlight_polygon 选中点样式
  getStyleByflag(flag, data, icon = '') {
    let style = null;
    switch (flag) {
      case 'default_point':
        this.defaultPointStyle.source.data = data;
        style = this.defaultPointStyle;
        break;
      case 'hightlight_point':
        this.highlightPointStyle.source.data = data;
        style = this.highlightPointStyle;
        break;
      case 'default_line':
        this.defaultLinetyle.source.data = data;
        style = this.defaultLinetyle;
        break;
      case 'lightstyle_line':
        this.lightLinetyle.source.data = data;
        style = this.lightLinetyle;
        break;
      case 'hightlight_line':
        this.highlightLinetyle.source.data = data;
        style = this.highlightLinetyle;
        break;
      case 'default_polygon':
        this.defaultPolygontyle.source.data = data;
        style = this.defaultPolygontyle;
        break;
      case 'hightlight_polygon':
        this.highlightPolygontyle.source.data = data;
        style = this.highlightPolygontyle;
        break;
      case 'animated_point':
        this.animatedDiffusionStyle.source.data = data;
        style = this.animatedDiffusionStyle;
        break;
      case 'hightlightrain_point':
        this.highlightRainPointStyle.source.data = data;
        style = this.highlightRainPointStyle;
        break;
      case 'hightlightrain_line':
        this.highlightRainLineStyle.source.data = data;
        style = this.highlightRainLineStyle;
        break;
      case 'hightlightsewage_point':
        this.highlightSewagePointStyle.source.data = data;
        style = this.highlightSewagePointStyle;
        break;
      case 'hightlightsewage_line':
        this.highlightSewageLineStyle.source.data = data;
        style = this.highlightSewageLineStyle;
        break;
      case 'question_point':
        this.questionPointStyle.source.data = data;
        style = this.questionPointStyle;
        break;
      case 'hl_question_point':
        this.highLightQuestionPointstyle.source.data = data;
        style = this.highLightQuestionPointstyle;
        break;
      case 'question_line':
        this.questionLineStyle.source.data = data;
        style = this.questionLineStyle;
        break;
      case 'question_polygon':
        this.questionPolyStyle.source.data = data;
        style = this.questionPolyStyle;
        break;
      case 'editIcon':
        this.editIcon.source.data = data;
        style = this.editIcon;
        break;
      case 'iquery_point':
        this.iQueryPointStyle.source.data = data;
        style = this.iQueryPointStyle;
        break;
      case 'iquery_line':
        this.iQueryLineStyle.source.data = data;
        style = this.iQueryLineStyle;
        break;
      default:
        this.iconStyle.source.data = data;
        style = this.iconStyle;
    }
    return style;
  }
  // 上图
  drawGeo(listData, style = 'default') {
    if (!Array.isArray(listData)) {
      return;
    }
    const geojson: any = this.geoListToGeoJson(listData);
    if (!geojson.features) {
      return;
    }
    const geoType = turf.getType(geojson.features[0]);
    let zoomCenter: any = [];
    switch (geoType) {
      case 'Point':
        // iconStyle.source.data = geojson;
        // pagePointStyle.source.data = geojson;
        const pagePointStyle = this.getStyleByflag(`${style}_point`, geojson);
        this.mapService.addGeoJSONLayer(pagePointStyle, {});
        zoomCenter = turf.center(geojson).geometry.coordinates;
        break;
      case 'MultiLineString':
        const pageLinetyle = this.getStyleByflag(`${style}_line`, geojson);
        this.mapService.addGeoJSONLayer(pageLinetyle, {});
        zoomCenter = turf.center(geojson).geometry.coordinates;
        break;
      case 'MultiPolygon':
        // iconStyle.source.data = this.getPolygonCenterCollenction(geojson);
        // pagePolygontyle.source.data = geojson;
        const pagePolygontyle = this.getStyleByflag(`${style}_polygon`, geojson);
        this.mapService.addGeoJSONLayer(pagePolygontyle, {});
        zoomCenter = turf.center(geojson).geometry.coordinates;
        break;
      default:
        break;
    }
  }
  geoListToGeoJson(list) {
    const result = { type: 'FeatureCollection', features: [] };
    list.forEach((item, index) => {
      item.index = index + 1;
      const geoItem = wellknown.parse(item.geo);
      result.features.push({ type: 'Feature', geometry: geoItem, properties: item });
    });

    return result;
  }
  // 取面要素中心点集合
  getPolygonCenterCollenction(geojson) {
    const result = {
      type: 'FeatureCollection',
      features: []
    };
    geojson.features.forEach(item => {
      const center = turf.center(item);
      center.properties = item.properties;

      result.features.push(center);
    });
    return result;
  }
  // 取线的第一个顶点
  getLineFirstPointCollection(geojson) {
    const result = {
      type: 'FeatureCollection',
      features: []
    };
    geojson.features.forEach(item => {
      const feature = {
        geometry: { type: 'Point', coordinates: item.geometry.coordinates[0][0] },
        properties: item.properties
      };
      result.features.push(feature);
    });
    return result;
  }
  // 得到鼠标点击时的屏木坐标
  mousePos(map, e) {
    const canvas = map.getCanvasContainer();
    const rect = canvas.getBoundingClientRect();
    return new mapboxgl.Point(
      e.clientX - rect.left - canvas.clientLeft,
      e.clientY - rect.top - canvas.clientTop
    );
  }
  // fitbounds 底图移动放到了到线bounds范围大小
  fitLineBounds(map, coordinates, zoomsize = 20) {
    const bounds = coordinates.reduce((bound, coord) => {
      return bound.extend(coord);
    },
      new mapboxgl.LngLatBounds(coordinates[0], coordinates[0]));
    map.fitBounds(bounds, {
      padding: 20,
      maxZoom: zoomsize
    });
  }
  // 计算polygon的bounds
  fitPolygonBoundingBox(mapbox, coordinates) {
    // bounds [xMin, yMin][xMax, yMax]
    const bounds = [[], []];
    let polygon;
    let latitude;
    let longitude;
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < coordinates.length; i++) {
      if (coordinates.length === 1) {
        // Polygon coordinates[0][nodes]
        polygon = coordinates[0];
      } else {
        // Polygon coordinates[poly][0][nodes]
        polygon = coordinates[i][0];
      }
      // tslint:disable-next-line:prefer-for-of
      for (let j = 0; j < polygon.length; j++) {
        longitude = polygon[j][0];
        latitude = polygon[j][1];

        bounds[0][0] = bounds[0][0] < longitude ? bounds[0][0] : longitude;
        bounds[1][0] = bounds[1][0] > longitude ? bounds[1][0] : longitude;
        bounds[0][1] = bounds[0][1] < latitude ? bounds[0][1] : latitude;
        bounds[1][1] = bounds[1][1] > latitude ? bounds[1][1] : latitude;
      }
    }
    mapbox.fitBounds(bounds, { padding: 200 });
  }
  // 添加图层；
  addLayer(mapboxglmap, layer) {
    const layersource = mapboxglmap.getSource(layer.source);
    if (!layersource) {
      mapboxglmap.addSource(
        layer.source,
        this.styleConfig.sources[layer.source]
      );
    }
    if (!layer) { return; }
    if (mapboxglmap.getLayer(layer.id)) {
      this.mapService.removeLayerByIds([layer.id]);
    }
    mapboxglmap.addLayer(layer);
    // }
  }
  removeLayers(keys) {
    this.mapService.removeLayerByIds(keys);
  }
  /**
  * 根据key获取图层样式
  * @param key ；
  */
  getLayerStyByKey(key) {
    const layerItem = this.styleConfig.layers.find((layer: any) => {
      return layer.id === key;
    });
    return layerItem;
  }
  getQuestionLayer() {
    return this.questionIDs;
  }
  getIQueryLayer() {
    return this.iQueryIDs;
  }

  getConfig() {
    return Promise.all([
      this.mapService.getMapStyle("mkzWrS9MR"),
      // this.getTreeKeyLyrIdConfig()
    ]);
  }
  /// multepoli的bounds计算定位
  getBoundingBox(data, map) {
    let bounds = {};
    let coords;
    let point;
    let latitude;
    let longitude;
    // We want to use the “features” key of the FeatureCollection (see above)
    data = data.features;
    // Loop through each “feature”
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < data.length; i++) {
      // Pull out the coordinates of this feature
      coords = data[i].geometry.coordinates[0];
      // For each individual coordinate in this feature's coordinates…
      // tslint:disable-next-line:prefer-for-of
      for (let j = 0; j < coords.length; j++) {
        point = coords[j];
        // tslint:disable-next-line:prefer-for-of
        for (let a = 0; a < point.length; a++) {
          longitude = point[a][0];
          latitude = point[a][1];
          // Update the bounds recursively by comparing the current
          // xMin/xMax and yMin/yMax with the coordinate
          // we're currently checking
          bounds['xMin'] = bounds['xMin'] < longitude ? bounds['xMin'] : longitude;
          bounds['xMax'] = bounds['xMax'] > longitude ? bounds['xMax'] : longitude;
          bounds['yMin'] = bounds['yMin'] < latitude ? bounds['yMin'] : latitude;
          bounds['yMax'] = bounds['yMax'] > latitude ? bounds['yMax'] : latitude;
        }
      }
    }
    // Returns an object that contains the bounds of this GeoJSON
    // data. The keys of this object describe a box formed by the
    // northwest (xMin, yMin) and southeast (xMax, yMax) coordinates.
    map.fitBounds([[bounds['xMin'], bounds['yMin']], [bounds['xMax'], bounds['yMax']]], 200);
    // return bounds;
  }
  getLayersIDlist() {
    return this.layerIDs;
  }
  getAnimationsIDlist() {
    return this.animationPoint;
  }

  setLayersIDlist(id) {
    this.layerIDs.push(id);
  }
}
